package io.wins.vertx.verticle.api;

import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.Seat;
import io.wins.vertx.service.SeatService;

public class SeatApiVerticle extends RestApiVerticle {

    public static final String REST_ADDRESS = "io.wins.rest.seat#%1$s";
    private static final Logger logger = LoggerFactory.getLogger(SeatApiVerticle.class);

    public final SeatService service;

    public SeatApiVerticle(final SeatService seatService) {
        this.service = seatService;
    }

    @Override
    public void start(final Future<Void> startFuture) throws Exception {
        super.start();
        this.on(String.format(REST_ADDRESS, CREATE), this::createSeat);
        this.on(String.format(REST_ADDRESS, LIST), this::listSeat);
        this.on(String.format(REST_ADDRESS, LOAD), this::loadSeat);
        this.on(String.format(REST_ADDRESS, UPDATE), this::updateSeat);
        this.on(String.format(REST_ADDRESS, DELETE), this::deleteSeat);
        startFuture.complete();
    }

    private void loadSeat(final Message<JsonObject> tMessage) {
        final String id = tMessage.body().getJsonObject("param").getString("id");
        this.service.getSeatById(id, tMessage);
    }

    private void deleteSeat(final Message<JsonObject> tMessage) {
        final String id = tMessage.body().getJsonObject("param").getString("id");
        this.service.deleteSeat(id, tMessage);
    }

    private void updateSeat(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("seat");
        final Seat seat = new Seat(body);
        this.service.updateSeat(seat, tMessage);
    }

    private void listSeat(final Message<JsonObject> tMessage) {
        this.service.listSeat(tMessage);
    }

    private void createSeat(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("seat");
        final Seat seat = new Seat(body);
        System.out.println(seat.toJson());
        this.service.createSeat(seat, tMessage);
    }
}
